package com.wkq.util

/**
 *
 *@Author: wkq
 *
 *@Time: 2025/4/11 11:26
 *
 *@Desc: Url 处理工具类
 */

import android.net.Uri
import android.text.TextUtils
import java.io.UnsupportedEncodingException
import java.net.URLEncoder
import java.nio.charset.StandardCharsets
import java.util.regex.Pattern


object UriUtil {


    fun extractSourceKey(key: String, input: String?): String? {
        if (input == null || input.isEmpty()) {
            return null
        }
        // 定义正则表达式
        val regex = "$key=([^,]+)"
        val pattern = Pattern.compile(regex)
        val matcher = pattern.matcher(input)

        if (matcher.find()) {
            // 提取匹配到的组
            return matcher.group(1)
        }
        return null
    }

    fun appendParameter(url: String, paramKey: String, paramValue: String): String {
        try {

            if (TextUtils.isEmpty(url) || TextUtils.isEmpty(paramKey)||url.contains(paramKey)) return url
            // 对参数值进行编码
            val encodedValue = URLEncoder.encode(paramValue, StandardCharsets.UTF_8.toString())
            // 检查 URL 中是否已经有参数
            val separator = if (url.contains("?")) "&" else "?"
            return "$url$separator$paramKey=$encodedValue"
        } catch (e: UnsupportedEncodingException) {

            return ""
        }
    }
    /**
     * 判断是否是Url
     */
    fun isUrl(url: String): Boolean {
        if (TextUtils.isEmpty(url)) return false
        return url.startsWith("http://") || url.startsWith("https://") || url.startsWith("ftp://")
    }


    /**
     * 获取查询参数名称
     */
    fun getQueryParameterNames(url: String): List<String> {
        if (TextUtils.isEmpty(url)) return emptyList()
        var uri = Uri.parse(url)

        if (uri.isOpaque()) {
            return emptyList()
        }
        var parameterNames = uri.queryParameterNames

        if (parameterNames == null) {
            return emptyList()
        } else {
            return parameterNames.toMutableList()
        }
    }

    /**
     * 获取Url的原来参数值
     */
    fun getQueryParameterValue(url: String, key: String): String? {

        if (TextUtils.isEmpty(url) || TextUtils.isEmpty(key)) return url
        var uri = Uri.parse(url)
        if (uri.isOpaque()) {
            return url
        }
        //利用Map的唯一性拼接参数
        var parameterMap = getParameterMap(url)
        return parameterMap.get(key)

    }

    /**
     *  获取Url参数的值(Decode之后的)
     *
     *  getQueryParameter()  方法是默认Decode的
     *
     */
    fun getQueryParameterDecodeValue(url: String, key: String): String? {
        if (TextUtils.isEmpty(url) || TextUtils.isEmpty(key)) return ""
        var uri = Uri.parse(url)
        if (uri.isOpaque()) {
            return ""
        } else {
            return Uri.parse(url).getQueryParameter(key)
        }
    }

    /**
     * url 添加参数
     */
    fun addQueryParameterValue(url: String, key: String, value: String): String {
        if (TextUtils.isEmpty(url) || TextUtils.isEmpty(key)) return url
        var uri = Uri.parse(url)
        if (uri.isOpaque()) {
            return url
        }

        if (url.contains("#")) {
            url.replace("#", "%23")
        }
        if (!url.contains("?")) {
            url + "?"
        }
        var urlStart = url.split("?").get(0)
        //利用Map的唯一性拼接参数
        var parameterMap = getParameterMap(url)
        //利用map的唯一性 存储或者更新值
        parameterMap.put(key, value)
        //参数的map
        var appendUrl = appendMapParameter(parameterMap)
        var division = "?"
        return "$urlStart$division$appendUrl"
    }

    /**
     * 删除Encode 的参数
     */
    fun deleteQueryParameterDecodeValue(url: String, key: String): String {
        if (TextUtils.isEmpty(url) || TextUtils.isEmpty(key)) return url
        var uri = Uri.parse(url)
        if (uri.isOpaque()) {
            return url
        }
        if (!url.contains("?")) {
            url + "?"
        }
        var urlStart = url.split("?").get(0)
        //利用Map的唯一性拼接参数
        var parameterMap = getParameterMap(url)
        //利用map的唯一性 存储或者更新值
        if (parameterMap.containsKey(key)){
            parameterMap.remove(key)
        }
        //参数的map
        var appendUrl = appendMapParameter(parameterMap)
        var division = "?"
        return "$urlStart$division$appendUrl"
    }

    /**
     * 田间Encode 的参数
     */
    fun addQueryParameterDecodeValue(url: String, key: String, value: String): String {
        if (TextUtils.isEmpty(url) || TextUtils.isEmpty(key)) return url
        var uri = Uri.parse(url)
        if (uri.isOpaque()) {
            return url
        }
        if (!url.contains("?")) {
            url + "?"
        }
        var urlStart = url.split("?").get(0)
        //利用Map的唯一性拼接参数
        var parameterMap = getParameterMap(url)
        //利用map的唯一性 存储或者更新值
        parameterMap.put(key, Uri.encode(value))
        //参数的map
        var appendUrl = appendMapParameter(parameterMap)
        var division = "?"
        return "$urlStart$division$appendUrl"
    }


    /**
     * map 拼接成字符串
     */
    private fun appendMapParameter(parameterMap: HashMap<String, String>): String {
        var stringBuilder = StringBuilder()

        parameterMap.keys.forEach {
            stringBuilder.append(it).append("=").append(parameterMap.get(it)).append("&")
        }
        if (stringBuilder.length > 0) {
            stringBuilder.deleteCharAt(stringBuilder.length - 1)
        }
        return stringBuilder.toString()
    }

    /**
     * 把url 的参数转为Map存储
     */
    private fun getParameterMap(
        url: String
    ): HashMap<String, String> {
        var map: HashMap<String, String> = HashMap<String, String>()
        // 参数名字的列表
        var parameter = Uri.parse(url).queryParameterNames
        parameter.forEach {
            if (getQueryParameterDecodeValue(url, it) != null)
                map.put(it, getQueryParameterDecodeValue(url, it)!!)
        }
        return map
    }


}